<template>
  <div class="init-container">
    <div class="mask-container" v-if="isMask"></div>
    <div class="task-statistics-container">
      <div class="real-time-statistics">
        <div class="header">
          <div class="title">实时任务统计</div>
          <!-- <div class="refresh" @click="handleRefresh">
            <i class="ivu-icon wy-icon wy-shuaxin13"></i>
            <span>刷新</span>
          </div> -->
          <Button
            type="primary"
            @click="handleRefresh"
            icon="ivu-icon wy-icon wy-shuaxin13"
            >刷新</Button
          >
        </div>
        <div class="real-time-section">
          <RealTimeChart
            type="daily"
            :data="realTimeTotalData"
            @refresh="handleRefresh"
          />
          <RealTimeChart
            type="process_daily"
            :data="realTimeProcessData"
            @refresh="handleRefresh"
          />
        </div>
      </div>
      <div class="history-statistics">
        <div class="header">
          <div class="title">历史任务统计</div>
          <div class="refresh" @click="handleRefresh">
            <i class="iconfont icon-shuaxin"></i>
          </div>
        </div>

        <div class="history-section">
          <HistoryChart
            type="history"
            :data="historyTotalData"
            :period="historyPeriod"
            :selectLine="historySelectLine"
            :dateRange="historyDateRange"
            @date-change="handleDateChange"
            @period-change="handlePeriodChange"
            @line-change="handleLineChange"
          />
          <HistoryChart
            type="process_history"
            :data="historyProcessData"
            :metric="historyMetric"
            :period="historyPrecessPeriod"
            :dateRange="historyProcessDataRange"
            @date-change="handleDateChange"
            @period-change="handlePeriodChange"
            @metric-change="handleMetricChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import RealTimeChart from './RealTimeChart.vue';
import HistoryChart from './HistoryChart.vue';
import { T_srv, Tsrv, vue, N_TaskStatistics, TIME_LIMITS } from './config';

@T_srv.comp({
  components: { RealTimeChart, HistoryChart }
})
export default class cTaskStatistics extends vue {
  private realTimeTotalData: N_TaskStatistics.realTimeTotalData = {
    hang_group: { pending: 1, processing: 2, completed: 3 },
    work_order: { pending: 2, processing: 3, completed: 4 },
    part: { pending: 3, processing: 4, completed: 5 }
  };

  private realTimeProcessData: N_TaskStatistics.realTimeProcessData[] = [
    { process: '硫酸阳极化', pending: 1, processing: 2, completed: 3 },
    { process: '铬酸阳极化', pending: 2, processing: 3, completed: 4 }
  ];

  private historyTotalData: N_TaskStatistics.historyTotalData[] = [
    { date: '2025年1月', hang_group: 1, work_order: 2, part: 3 },
    { date: '2025年2月', hang_group: 2, work_order: 3, part: 4 },
    { date: '2025年3月', hang_group: 3, work_order: 4, part: 5 }
  ];

  private historyProcessData: N_TaskStatistics.historyProcessData[] = [
    { date: '2025年1月', process: '硫酸阳极化', num: 11 },
    { date: '2025年2月', process: '硫酸阳极化', num: 22 },
    { date: '2025年3月', process: '硫酸阳极化', num: 33 },
    { date: '2025年1月', process: '铬酸阳极化', num: 44 },
    { date: '2025年2月', process: '铬酸阳极化', num: 55 },
    { date: '2025年3月', process: '铬酸阳极化', num: 66 }
  ];

  // 默认展示最近三个月
  private historyPeriod: N_TaskStatistics.PeriodType = 'month';

  private historyPrecessPeriod: N_TaskStatistics.PeriodType = 'month';

  private historyMetric: N_TaskStatistics.CategoryType = 'hang_group';

  private historySelectLine: N_TaskStatistics.CategoryType[] = [
    'hang_group',
    'work_order',
    'part'
  ];

  // 默认展示最近三个月
  private historyDateRange: [Date, Date] = [
    new Date(new Date().getTime() - 3 * 30 * 24 * 60 * 60 * 1000),
    new Date()
  ];

  private historyProcessDataRange: [Date, Date] = [
    new Date(new Date().getTime() - 3 * 30 * 24 * 60 * 60 * 1000),
    new Date()
  ];

  private isMask: boolean = false;

  private get historyDateRangeDiff() {
    return (
      new Date(this.historyDateRange[1]).getTime() -
      new Date(this.historyDateRange[0]).getTime()
    );
  }

  private get historyProcessDataRangeDiff() {
    return (
      new Date(this.historyProcessDataRange[1]).getTime() -
      new Date(this.historyProcessDataRange[0]).getTime()
    );
  }

  async mounted() {
    await this.loadData();
  }

  private async loadData() {
    try {
      this.handleRealTimeTotalChange();
      this.handleRealTimeProcessChange();
      this.handleHistoryTotalChange();
      this.handleHistoryProcessChange();
    } catch (error) {
      console.error('数据加载失败:', error);
    }
  }

  private autoAdjustPeriod(rangeType: 'history' | 'process') {
    const diff =
      rangeType === 'history'
        ? this.historyDateRangeDiff
        : this.historyProcessDataRangeDiff;

    if (rangeType === 'history') {
      if (diff > TIME_LIMITS.YEARS_3) {
        if (
          this.historyPeriod === 'quarter' ||
          this.historyPeriod === 'month' ||
          this.historyPeriod === 'week' ||
          this.historyPeriod === 'day'
        ) {
          this.historyPeriod = 'year';
        }
      } else if (diff > TIME_LIMITS.QUARTERS_3) {
        if (
          this.historyPeriod === 'month' ||
          this.historyPeriod === 'week' ||
          this.historyPeriod === 'day'
        ) {
          this.historyPeriod = 'quarter';
        }
      } else if (diff > TIME_LIMITS.MONTHS_3) {
        if (this.historyPeriod === 'week' || this.historyPeriod === 'day') {
          this.historyPeriod = 'month';
        }
      } else if (diff > TIME_LIMITS.DAYS_21) {
        if (this.historyPeriod === 'day') {
          this.historyPeriod = 'week';
        }
      }
    } else {
      if (diff > TIME_LIMITS.YEARS_3) {
        if (
          this.historyPrecessPeriod === 'quarter' ||
          this.historyPrecessPeriod === 'month' ||
          this.historyPrecessPeriod === 'week' ||
          this.historyPrecessPeriod === 'day'
        ) {
          this.historyPrecessPeriod = 'year';
        }
      } else if (diff > TIME_LIMITS.QUARTERS_3) {
        if (
          this.historyPrecessPeriod === 'month' ||
          this.historyPrecessPeriod === 'week' ||
          this.historyPrecessPeriod === 'day'
        ) {
          this.historyPrecessPeriod = 'quarter';
        }
      } else if (diff > TIME_LIMITS.MONTHS_3) {
        if (
          this.historyPrecessPeriod === 'week' ||
          this.historyPrecessPeriod === 'day'
        ) {
          this.historyPrecessPeriod = 'month';
        }
      } else if (diff > TIME_LIMITS.DAYS_21) {
        if (this.historyPrecessPeriod === 'day') {
          this.historyPrecessPeriod = 'week';
        }
      }
    }
  }

  // 通用数据请求方法
  private async fetchData(
    request: () => N_TaskStatistics.TaskStatisticsRequest,
    setData: (data: any) => void
  ) {
    try {
      const res = await Tsrv.doEvent(
        'task_statics',
        Tsrv.getFunInfo('cTaskStatistics'),
        request,
        false
      );

      if (res.isErr()) {
        this.$msg(res.errmsg);
        return;
      }

      const conf = res.getReturnData('conf');
      if (Tsrv.noValue(conf) || !conf.res?.data || !conf.res.success) {
        return;
      }

      setData(conf.res.data);
    } catch (error) {
      console.error('数据请求失败:', error);
    }
  }

  private async handleRefresh() {
    await this.loadData();
  }

  // 统一处理数据更新
  private handleDataChange(
    type: N_TaskStatistics.QueryType,
    request: () => N_TaskStatistics.TaskStatisticsRequest,
    setData: (data: any) => void
  ) {
    this.fetchData(request, data => {
      if (data.query_type === type) {
        setData(data.data);
      }
    });
  }

  // 加载当天任务量统计
  private handleRealTimeTotalChange() {
    this.handleDataChange(
      'daily',
      () => ({
        funName: 'cTaskStatistics',
        title: 'customButton',
        from: 'cTaskStatistics',
        data: {
          query_type: 'daily',
          date: this.formatDate(new Date()),
          status: ['0', '5', '6'],
          category: ['hang_group', 'work_order', 'part']
        }
      }),
      data => {
        this.realTimeTotalData = data;
      }
    );
  }

  // 按工艺统计当天挂组数
  private handleRealTimeProcessChange() {
    this.handleDataChange(
      'process_daily',
      () => ({
        funName: 'cTaskStatistics',
        title: 'customButton',
        from: 'cTaskStatistics',
        data: {
          query_type: 'process_daily',
          date: this.formatDate(new Date()),
          status: ['0', '5', '6'],
          category: ['hang_group']
        }
      }),
      data => {
        this.realTimeProcessData = data;
      }
    );
  }

  // 加载历史任务量统计
  private handleHistoryTotalChange() {
    this.handleDataChange(
      'history',
      () => ({
        funName: 'cTaskStatistics',
        title: 'customButton',
        from: 'cTaskStatistics',
        data: {
          query_type: 'history',
          date: [
            this.formatDate(this.historyDateRange[0]),
            this.formatDate(this.historyDateRange[1])
          ],
          // status: ['0', '5', '6'],
          category: ['hang_group', 'work_order', 'part'],
          period: this.historyPeriod
        }
      }),
      data => {
        this.historyTotalData = data;
      }
    );
  }

  // 按工艺统计历史任务量
  private handleHistoryProcessChange() {
    this.handleDataChange(
      'process_history',
      () => ({
        funName: 'cTaskStatistics',
        title: 'customButton',
        from: 'cTaskStatistics',
        data: {
          query_type: 'process_history',
          date: [
            this.formatDate(this.historyProcessDataRange[0]),
            this.formatDate(this.historyProcessDataRange[1])
          ],
          category: [this.historyMetric],
          period: this.historyPrecessPeriod
        }
      }),
      data => {
        this.historyProcessData = data;
      }
    );
  }

  private formatDate(date, includeTime = false) {
    if (typeof date === 'string') date = new Date(date);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要加1
    const day = String(date.getDate()).padStart(2, '0');

    if (includeTime) {
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }
    return `${year}-${month}-${day}`;
  }

  private async handlePeriodChange(
    period: N_TaskStatistics.PeriodType,
    type: 'history' | 'process_history'
  ) {
    if (type === 'history') {
      this.historyPeriod = period;
      this.handleHistoryTotalChange();
    } else if (type === 'process_history') {
      this.historyPrecessPeriod = period;
      this.handleHistoryProcessChange();
    }
  }

  private handleMetricChange(metric: N_TaskStatistics.CategoryType) {
    this.historyMetric = metric;
    this.handleHistoryProcessChange();
  }

  private handleDateChange(param: {
    dates: [Date, Date];
    type: 'history' | 'process_history';
  }) {
    if (param.type === 'history') {
      this.historyDateRange = param.dates;
      this.autoAdjustPeriod('history');
      // 加载对应日期范围的数据，历史任务量统计
      this.handleHistoryTotalChange();
    } else if (param.type === 'process_history') {
      this.historyProcessDataRange = param.dates;
      this.autoAdjustPeriod('process');
      // 按工艺统计任务量
      this.handleHistoryProcessChange();
    }
  }

  private handleLineChange(lines: N_TaskStatistics.CategoryType[]) {
    this.historySelectLine = lines;
  }
}
</script>

<style lang="scss" scoped>
.task-statistics-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 24px;
  background-color: #e9ecf3;

  .real-time-statistics,
  .history-statistics {
    height: 50%;
  }

  .real-time-section,
  .history-section {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
    // height: 50%;
    height: calc(100% - 36px);
  }

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .title {
      font-size: 20px;
      font-weight: bold;
      margin-bottom: 16px;
    }

    .refresh {
      cursor: pointer;
      position: absolute;
      top: 16px;
      right: 16px;
      font-size: 16px;
    }
  }
}
</style>
